import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/index'
  },
  {
    path: '/index',
    component: () => import('../views/user/index.vue'),
    redirect: '/home',
    children: [
      {
        path: '/home',
        component: () => import('../views/user/Home.vue')
      },
      {
        path: '/slider/:action?',
        component: () => import('../views/user/Order.vue'),
        props: {
          action: 1 // 设置默认值为 1
        }
      },
      {
        path: '/cart',
        component: () => import('../views/user/Cart.vue')
      },
      {
        path: '/login',
        component: () => import('../views/user/Login.vue')
      },
      {
        path: '/suggestion',
        component: () => import('../views/user/Suggestion.vue')
      },
      {
        path: '/indProduct/:id', // :id 表示这是一个动态的路径参数
        component: () => import('../views/user/Product.vue') // 对应新页面的组件
      },
      {
        path: '/category/:name',
        component: () => import('../views/user/Category.vue')
      },
      {
        path: '/buy',
        component: () => import('../views/user/order/Buy.vue')
      },
      {
        path: '/search',
        component: () => import('../views/user/Search.vue')
      },
      {
        path: '/personal-center',
        component: () => import('../views/user/PersonalCenter.vue')
      }
    ]
  },
  {
    path: '/admin/home',
    redirect: '/admin'
  },
  {
    path: '/admin',
    component: () => import('../views/admin/Home.vue'),
    // 管理员登录路由守卫
    beforeEnter: (to, from, next) => {
      const adminToken = window.localStorage.getItem('adminToken')
      if (!adminToken && to.name !== '/admingLogin') {
        next('/adminLogin')
      } else {
        next()
      }
    },
    redirect: '/admin/welcome',
    children: [
      {
        path: 'welcome',
        component: () => import('../views/admin/Welcome.vue')
      },
      {
        path: 'user',
        component: () => import('../views/admin/user/Admin.vue')
      },
      {
        path: 'menber',
        component: () => import('../views/admin/user/Menber.vue')
      },
      {
        path: 'pet',
        component: () => import('../views/admin/goods/pet.vue')
      },
      {
        path: 'goods',
        component: () => import('../views/admin/goods/product.vue')
      },
      {
        path: 'website',
        component: () => import('../views/admin/manage/website.vue')
      },
      {
        path: 'merchant',
        component: () => import('../views/admin/user/Merchant.vue')
      },
      {
        path: 'categoties',
        component: () => import('../views/admin/goods/categoties.vue')
      },
      {
        path: 'slider',
        component: () => import('../views/admin/slider.vue')
      },
      {
        path: 'orders',
        component: () => import('../views/admin/order/Order.vue')
      },
      {
        path: 'report',
        component: () => import('../views/admin/report/Report.vue')
      },
      {
        path: 'product/add',
        component: () => import('../views/admin/goods/add.vue')
      },
      {
        path: 'product/modify',
        component: () => import('../views/admin/goods/modify.vue')
      }
    ]
  },
  {
    path: '/merchant-home',
    redirect: '/home',
    component: () => import('../views/merchant/Home.vue'),
    // 商家登录路由守卫
    beforeEnter: (to, from, next) => {
      if (to.path === '/merchantLogin' && to.name !== '/merchantLogin') return next()
      const tokenStr = window.localStorage.getItem('merchantToken')
      if (!tokenStr) return next('/merchantLogin')
      next()
    },
    children: [
      {
        path: '/home',
        component: () => import('../views/merchant/Home.vue')
      },
      {
        path: '/',
        component: () => import('../views/admin/Welcome.vue')
      },
      {
        path: 'employee',
        component: () => import('../views/merchant/employee/Employee.vue')
      },
      {
        path: 'order',
        component: () => import('../views/merchant/order/Order.vue')
      },
      {
        path: 'product',
        component: () => import('../views/merchant/product/Product.vue')
      },
      {
        path: 'add',
        component: () => import('../views/merchant/product/add.vue')
      },
      {
        path: 'modify',
        component: () => import('../views/merchant/product/modify.vue')
      }
    ]
  },
  {
    path: '/merchantLogin',
    component: () => import('../views/merchant/Login.vue')
  },
  {
    path: '/adminLogin',
    component: () => import('../views/admin/Login.vue')
  },
  // 其他没有匹配到路由的页面都重定向到这里
  {
    path: '/*',
    component: () => import('../components/404.vue')
  }
]

const router = new VueRouter({
  routes,
  mode: 'history'
})

// 禁止重复导航的报错
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

export default router

// 全局守卫
router.beforeEach((to, from, next) => {
  // 公共路径，任何人都可以访问
  const freePaths = ['/', '/home', '/login', '/indProduct/:id', '/category/:name', '/search']
  // 检查即将访问的路径是否在免登录名单中
  const isFreePath = freePaths.some(path =>
    to.path.match(new RegExp(`^${path}$`)) || to.path.includes('/indProduct/') || to.path.includes('/category/')
  )
  if (isFreePath) {
    // 免登录路径，直接放行
    next()
  } else if (to.path.startsWith('/admin')) {
    // 管理员页面的逻辑
    const adminToken = window.localStorage.getItem('adminToken')
    if (!adminToken && to.path !== '/adminLogin') {
      // 未登录，重定向到管理员登录页面
      next('/adminLogin')
    } else {
      // 已登录，放行
      next()
    }
  } else if (to.path.startsWith('/merchant')) {
    // 商家页面的逻辑
    const merchantToken = window.localStorage.getItem('merchantToken')
    if (!merchantToken && to.path !== '/merchantLogin') {
      // 未登录，重定向到商家登录页面
      next('/merchantLogin')
    } else {
      // 已登录，放行
      next()
    }
  } else {
    if (isAuthenticated()) {
        next()
    } else {
      next('/login')
    }
  }
})

function isAuthenticated() {
  const tokenStr = window.localStorage.getItem('userToken')
  if (tokenStr !== null) {
    return true
  }
  return false
}
